import tkinter as tk
from tkinter import ttk
import customtkinter
from core.utils.logger import debug, info, error
from core.services.data_manager import DataManager

# 配置 CustomTkinter 外观模式
customtkinter.set_appearance_mode("System")  # "System", "Dark", or "Light"
customtkinter.set_default_color_theme("blue")  # "blue", "green", or "dark-blue"

class Theme:
    # 主题配置
    THEMES = {
        'light': {
            'bg_primary': '#FFFFFF',
            'bg_secondary': '#F8F9FA',
            'bg_tertiary': '#ECF0F1',
            'fg_primary': '#2C3E50',
            'fg_secondary': '#7F8C8D',
            'fg_tertiary': '#95A5A6',
            'accent': '#FF6B35',
            'accent_hover': '#FF8C5A',
            'accent_pressed': '#E55A2B',
            'success': '#27AE60',
            'warning': '#E67E22',
            'error': '#E74C3C',
            'border': '#BDC3C7'
        },
        'dark': {
            'bg_primary': '#1E1E1E',
            'bg_secondary': '#2D2D2D',
            'bg_tertiary': '#3C3C3C',
            'fg_primary': '#E0E0E0',
            'fg_secondary': '#B0B0B0',
            'fg_tertiary': '#808080',
            'accent': '#FF6B35',
            'accent_hover': '#FF8C5A',
            'accent_pressed': '#E55A2B',
            'success': '#2ECC71',
            'warning': '#F39C12',
            'error': '#E74C3C',
            'border': '#404040'
        }
    }
    
    # 字体大小配置
    FONT_SIZES = {
        'small': {
            'base': 9,
            'small': 8,
            'large': 11,
            'title': 14,
            'heading': 12
        },
        'medium': {
            'base': 10,
            'small': 9,
            'large': 12,
            'title': 16,
            'heading': 14
        },
        'large': {
            'base': 12,
            'small': 10,
            'large': 14,
            'title': 18,
            'heading': 16
        }
    }
    
    _current_theme = 'light'
    _current_font_size = 'medium'
    
    @classmethod
    def configure_styles(cls):
        """配置样式"""
        try:
            # 加载用户设置
            cls._load_user_settings()
            
            # 同步 CustomTkinter 主题
            cls.sync_theme_to_customtkinter()
            
            # 应用主题
            cls._apply_theme()
            
            info(f"Theme configured: {cls._current_theme}, font size: {cls._current_font_size}")
            
        except Exception as e:
            error(f"Failed to configure theme: {e}")
            # 使用默认配置
            cls._apply_default_theme()
    
    @classmethod
    def _load_user_settings(cls):
        """加载用户设置"""
        try:
            dm = DataManager()
            settings = dm.load_data('settings.json') or {}
            cls._current_theme = settings.get('theme', 'light').lower()
            cls._current_font_size = settings.get('font_size', 'medium').lower()
            
            # 验证设置
            if cls._current_theme not in cls.THEMES:
                cls._current_theme = 'light'
            if cls._current_font_size not in cls.FONT_SIZES:
                cls._current_font_size = 'medium'
                
        except Exception as e:
            error(f"Failed to load user settings: {e}")
            cls._current_theme = 'light'
            cls._current_font_size = 'medium'
    
    @classmethod
    def _apply_theme(cls):
        """应用当前主题"""
        try:
            style = ttk.Style()
            style.theme_use('clam')
            
            theme_colors = cls.THEMES[cls._current_theme]
            font_sizes = cls.FONT_SIZES[cls._current_font_size]
            
            # 基础样式
            style.configure('.', 
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['base']))
            
            # 主要按钮样式（橙色主题）
            style.configure('Accent.TButton', 
                           foreground='white', 
                           background=theme_colors['accent'],
                           focuscolor='none',
                           font=('Arial', font_sizes['base'], 'bold'),
                           padding=(10, 6))
            
            # 危险按钮样式（红色主题）
            style.configure('Danger.TButton', 
                           foreground='white', 
                           background='#E74C3C',
                           focuscolor='none',
                           font=('Arial', font_sizes['base'], 'bold'),
                           padding=(10, 6))
            
            style.map('Accent.TButton',
                     background=[('active', theme_colors['accent_hover']),
                               ('pressed', theme_colors['accent_pressed'])])
            
            style.map('Danger.TButton',
                     background=[('active', '#C0392B'),
                               ('pressed', '#A93226')])
            
            # 导航按钮样式
            style.configure('Nav.TButton',
                           font=('Arial', font_sizes['base']),
                           padding=(10, 5),
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'])
            
            # 分类按钮样式
            style.configure('Category.TButton',
                           font=('Arial', font_sizes['small']),
                           padding=(8, 3),
                           background=theme_colors['bg_secondary'],
                           foreground=theme_colors['fg_primary'])
            
            # 框架样式
            style.configure('Navbar.TFrame', background=theme_colors['bg_tertiary'])
            style.configure('Welcome.TFrame', background=theme_colors['bg_tertiary'])
            style.configure('Card.TFrame', 
                           background=theme_colors['bg_secondary'],
                           relief='solid',
                           borderwidth=1)
            
            # 标签样式
            style.configure('Title.TLabel',
                           font=('Arial', font_sizes['title'], 'bold'),
                           foreground=theme_colors['fg_primary'],
                           background=theme_colors['bg_primary'])
            
            style.configure('Heading.TLabel',
                           font=('Arial', font_sizes['heading'], 'bold'),
                           foreground=theme_colors['fg_primary'],
                           background=theme_colors['bg_primary'])
            
            style.configure('Secondary.TLabel',
                           font=('Arial', font_sizes['base']),
                           foreground=theme_colors['fg_secondary'],
                           background=theme_colors['bg_primary'])
            
            # 输入框样式
            style.configure('TEntry',
                           fieldbackground=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           borderwidth=1,
                           relief='solid')
            
            # 组合框样式
            style.configure('TCombobox',
                           fieldbackground=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           borderwidth=1,
                           relief='solid')
            
            # 复选框样式
            style.configure('TCheckbutton',
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['base']),
                           indicatordiameter=16,
                           indicatormargin=5,
                           indicatorrelief='flat')
            
            style.map('TCheckbutton',
                     background=[('active', theme_colors['bg_primary'])],
                     indicatorcolor=[('selected', theme_colors['accent']),
                                   ('!selected', theme_colors['bg_secondary'])])
            
            # 单选按钮样式
            style.configure('TRadiobutton',
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['base']))
            
            # 标签框架样式
            style.configure('TLabelframe',
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['base'], 'bold'))
            
            style.configure('TLabelframe.Label',
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['base'], 'bold'))
            
            # 滚动条样式
            style.configure('TScrollbar',
                           background=theme_colors['bg_secondary'],
                           troughcolor=theme_colors['bg_tertiary'],
                           borderwidth=0,
                           arrowcolor=theme_colors['fg_secondary'])
            
            # 管理员页面样式
            cls._configure_admin_styles(style, theme_colors, font_sizes)
            
            debug(f"✅ Theme applied: {cls._current_theme}")
            
        except Exception as e:
            error(f"Failed to apply theme: {e}")
            cls._apply_default_theme()
    
    @classmethod
    def _configure_admin_styles(cls, style, theme_colors, font_sizes):
        """配置管理员页面专用样式"""
        try:
            # 管理员头部样式
            style.configure('AdminHeader.TFrame',
                           background='#34495E',
                           relief='flat')
            
            # 管理员标签页样式
            style.configure('AdminTab.TFrame',
                           background='#ECF0F1',
                           relief='flat')
            
            style.configure('AdminTab.TButton',
                           background='#BDC3C7',
                           foreground='#2C3E50',
                           font=('Arial', font_sizes['base'], 'bold'),
                           padding=(15, 8),
                           relief='flat')
            
            style.map('AdminTab.TButton',
                     background=[('active', '#95A5A6'),
                               ('pressed', '#7F8C8D')])
            
            style.configure('AdminTabSelected.TButton',
                           background='#3498DB',
                           foreground='white',
                           font=('Arial', font_sizes['base'], 'bold'),
                           padding=(15, 8),
                           relief='flat')
            
            # 管理员内容区域样式
            style.configure('AdminContent.TFrame',
                           background=theme_colors['bg_primary'],
                           relief='flat')
            
            # 管理员退出按钮样式
            style.configure('AdminLogout.TButton',
                           background='#E74C3C',
                           foreground='white',
                           font=('Arial', font_sizes['base'], 'bold'),
                           padding=(10, 5),
                           relief='flat')
            
            style.map('AdminLogout.TButton',
                     background=[('active', '#C0392B'),
                               ('pressed', '#A93226')])
            
            # 管理员表格样式
            style.configure('Admin.Treeview',
                           background=theme_colors['bg_primary'],
                           foreground=theme_colors['fg_primary'],
                           font=('Arial', font_sizes['small']),
                           rowheight=25)
            
            style.configure('Admin.Treeview.Heading',
                           background='#34495E',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           relief='flat')
            
            style.map('Admin.Treeview',
                     background=[('selected', '#3498DB')])
            
            # 管理员卡片样式
            style.configure('AdminCard.TFrame',
                           background=theme_colors['bg_secondary'],
                           relief='raised',
                           borderwidth=1)
            
            # 管理员状态标签样式
            style.configure('StatusPending.TLabel',
                           background='#F39C12',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           padding=(8, 3))
            
            style.configure('StatusPaid.TLabel',
                           background='#3498DB',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           padding=(8, 3))
            
            style.configure('StatusShipped.TLabel',
                           background='#9B59B6',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           padding=(8, 3))
            
            style.configure('StatusCompleted.TLabel',
                           background='#27AE60',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           padding=(8, 3))
            
            style.configure('StatusCancelled.TLabel',
                           background='#95A5A6',
                           foreground='white',
                           font=('Arial', font_sizes['small'], 'bold'),
                           padding=(8, 3))
            
            debug("✅ Admin styles configured")
            
        except Exception as e:
            error(f"Failed to configure admin styles: {e}")
    
    @classmethod
    def _apply_default_theme(cls):
        """应用默认主题（备用）"""
        try:
            style = ttk.Style()
            style.theme_use('clam')
            
            # 基础样式
            style.configure('.', 
                           background='#FFFFFF',
                           foreground='#2C3E50',
                           font=('Arial', 10))
            
            # 主要按钮样式
            style.configure('Accent.TButton', 
                           foreground='white', 
                           background='#FF6B35',
                           focuscolor='none',
                           font=('Arial', 10, 'bold'),
                           padding=(10, 6))
            
            style.map('Accent.TButton',
                     background=[('active', '#FF8C5A'),
                               ('pressed', '#E55A2B')])
            
            # 其他样式
            style.configure('Nav.TButton',
                           font=('Arial', 10),
                           padding=(10, 5))
            
            style.configure('Category.TButton',
                           font=('Arial', 9),
                           padding=(8, 3))
            
            style.configure('Navbar.TFrame', background='#2C3E50')
            style.configure('Welcome.TFrame', background='#ECF0F1')
            
            debug("✅ Default theme applied")
            
        except Exception as e:
            error(f"Failed to apply default theme: {e}")
    
    @classmethod
    def set_theme(cls, theme_name):
        """设置主题"""
        if theme_name.lower() in cls.THEMES:
            cls._current_theme = theme_name.lower()
            cls._apply_theme()
            cls._save_settings()
            return True
        return False
    
    @classmethod
    def set_font_size(cls, size_name):
        """设置字体大小"""
        if size_name.lower() in cls.FONT_SIZES:
            cls._current_font_size = size_name.lower()
            cls._apply_theme()
            cls._save_settings()
            return True
        return False
    
    @classmethod
    def _save_settings(cls):
        """保存设置到文件"""
        try:
            dm = DataManager()
            settings = dm.load_data('settings.json') or {}
            settings['theme'] = cls._current_theme
            settings['font_size'] = cls._current_font_size
            dm.save_data('settings.json', settings)
            debug(f"💾 Settings saved: theme={cls._current_theme}, font_size={cls._current_font_size}")
        except Exception as e:
            error(f"Failed to save theme settings: {e}")
    
    @classmethod
    def get_current_theme(cls):
        """获取当前主题"""
        return cls._current_theme
    
    @classmethod
    def get_current_font_size(cls):
        """获取当前字体大小"""
        return cls._current_font_size
    
    @classmethod
    def get_available_themes(cls):
        """获取可用主题列表"""
        return list(cls.THEMES.keys())
    
    @classmethod
    def get_available_font_sizes(cls):
        """获取可用字体大小列表"""
        return list(cls.FONT_SIZES.keys())
    
    @classmethod
    def get_theme_colors(cls, theme_name=None):
        """获取主题颜色"""
        if theme_name is None:
            theme_name = cls._current_theme
        return cls.THEMES.get(theme_name, cls.THEMES['light'])
    
    @classmethod
    def get_font_sizes(cls, size_name=None):
        """获取字体大小配置"""
        if size_name is None:
            size_name = cls._current_font_size
        return cls.FONT_SIZES.get(size_name, cls.FONT_SIZES['medium'])
    
    @classmethod
    def get_color(cls, color_name, theme_name=None):
        """获取指定主题的颜色值
        
        Args:
            color_name: 颜色名称 (如 'bg_primary', 'fg_primary', 'accent')
            theme_name: 主题名称，如果为None则使用当前主题
            
        Returns:
            str: 颜色值（十六进制格式）
        """
        if theme_name is None:
            theme_name = cls._current_theme
        
        theme = cls.THEMES.get(theme_name, cls.THEMES['light'])
        return theme.get(color_name, '#000000')
    
    @classmethod
    def is_dark_mode(cls):
        """检查当前是否处于深色模式"""
        return cls._current_theme == 'dark'
    
    @classmethod
    def refresh_theme(cls):
        """刷新主题，重新应用所有样式"""
        cls._apply_theme()
    
    @classmethod
    def set_customtkinter_appearance(cls, mode):
        """设置 CustomTkinter 外观模式
        
        Args:
            mode: "System", "Dark", or "Light"
        """
        try:
            customtkinter.set_appearance_mode(mode)
            info(f"CustomTkinter appearance mode set to: {mode}")
        except Exception as e:
            error(f"Failed to set CustomTkinter appearance mode: {e}")
    
    @classmethod
    def set_customtkinter_color_theme(cls, theme):
        """设置 CustomTkinter 颜色主题
        
        Args:
            theme: "blue", "green", or "dark-blue"
        """
        try:
            customtkinter.set_default_color_theme(theme)
            info(f"CustomTkinter color theme set to: {theme}")
        except Exception as e:
            error(f"Failed to set CustomTkinter color theme: {e}")
    
    @classmethod
    def sync_theme_to_customtkinter(cls):
        """将当前主题同步到 CustomTkinter"""
        try:
            # 根据当前主题设置 CustomTkinter 外观模式
            if cls._current_theme == 'dark':
                customtkinter.set_appearance_mode("Dark")
            else:
                customtkinter.set_appearance_mode("Light")
            info(f"Synced CustomTkinter theme to: {cls._current_theme}")
        except Exception as e:
            error(f"Failed to sync theme to CustomTkinter: {e}")